package com.yfore.jfinal.pdf.plugin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.jsoup.helper.StringUtil;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.jfinal.plugin.IPlugin;

/**
 * 
 * @author farmer
 *
 */
public class PdfPlugin implements IPlugin{
	
	/**
	 * iTextRenderer 实例
	 */
	ITextRenderer iTextRenderer = ITextRendererObjectFactory.createTextRenderer();
	
	private List<String> fonts = null;
	
	/**
	 * 
	 * @param fonts
	 * 	外部字体路径
	 */
	public PdfPlugin(List<String> fonts){
		this.fonts = fonts==null?new ArrayList<String>():fonts;
		InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("fontPath.properties");
		if (null != resourceAsStream) {
			try {
				Properties properties = new Properties();
				properties.load(resourceAsStream);
				String fontPath = properties.getProperty("fontPath");
				if (!StringUtil.isBlank(fontPath)) {
					String[] splitPath = fontPath.split(";");
					if (splitPath.length > 0) {
						for (String path : splitPath) {
							this.fonts.add(path);
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public boolean start() {
		for (String font : fonts) {	//添加字体到ITextRenderer
			if(new File(font).isDirectory()){
				ITextRendererObjectFactory.addFonts(font);
			}else{
				ITextRendererObjectFactory.addFont(font);
			}
		}
		PdfKit.init(iTextRenderer);
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

	
	
}
